package com.yang.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.Random;

/**
 * 数据库连接池示例 - 信号量的经典应用场景
 * 使用信号量控制数据库连接池的大小，限制同时使用的连接数
 */
public class DatabaseConnectionPool {
    
    // 模拟数据库连接池，最多5个连接
    private static final int MAX_CONNECTIONS = 5;
    private static final Semaphore connectionSemaphore = new Semaphore(MAX_CONNECTIONS);
    
    // 模拟连接池中的连接
    private static final String[] connections = {
        "Connection-1", "Connection-2", "Connection-3", 
        "Connection-4", "Connection-5"
    };
    
    // 标记连接是否被使用
    private static final boolean[] used = new boolean[MAX_CONNECTIONS];
    
    public static void main(String[] args) {
        System.out.println("数据库连接池启动，最大连接数: " + MAX_CONNECTIONS);
        
        // 创建8个客户端线程，模拟并发数据库访问
        for (int i = 1; i <= 8; i++) {
            Thread client = new Thread(new DatabaseClient(i));
            client.start();
        }
    }
    
    /**
     * 获取数据库连接
     */
    public static String getConnection(int clientId) throws InterruptedException {
        System.out.println("客户端 " + clientId + " 请求数据库连接...");
        
        // 尝试获取连接许可，最多等待3秒
        if (connectionSemaphore.tryAcquire(3, TimeUnit.SECONDS)) {
            // 找到一个可用的连接
            synchronized (connections) {
                for (int i = 0; i < MAX_CONNECTIONS; i++) {
                    if (!used[i]) {
                        used[i] = true;
                        System.out.println("客户端 " + clientId + " 获得连接: " + connections[i]);
                        return connections[i];
                    }
                }
            }
        }
        
        System.out.println("客户端 " + clientId + " 获取连接超时！");
        return null;
    }
    
    /**
     * 释放数据库连接
     */
    public static void releaseConnection(String connection, int clientId) {
        if (connection != null) {
            synchronized (connections) {
                for (int i = 0; i < MAX_CONNECTIONS; i++) {
                    if (connections[i].equals(connection)) {
                        used[i] = false;
                        System.out.println("客户端 " + clientId + " 释放连接: " + connection);
                        break;
                    }
                }
            }
            // 释放信号量许可
            connectionSemaphore.release();
        }
    }
    
    static class DatabaseClient implements Runnable {
        private final int clientId;
        private final Random random = new Random();
        
        public DatabaseClient(int clientId) {
            this.clientId = clientId;
        }
        
        @Override
        public void run() {
            String connection = null;
            try {
                // 获取数据库连接
                connection = getConnection(clientId);
                
                if (connection != null) {
                    // 模拟数据库操作时间（1-4秒）
                    int workTime = 1000 + random.nextInt(3000);
                    System.out.println("客户端 " + clientId + " 使用 " + connection + " 执行数据库操作，预计耗时: " + workTime + "ms");
                    Thread.sleep(workTime);
                    System.out.println("客户端 " + clientId + " 完成数据库操作");
                }
                
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("客户端 " + clientId + " 被中断");
            } finally {
                // 确保连接被释放
                releaseConnection(connection, clientId);
            }
        }
    }
}
